package cn.wolfcode.mq;



import cn.wolfcode.config.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
@RocketMQMessageListener(consumerGroup = "MQSeckillResultListener",topic =MQConstant.ORDER_RESULT_TOPIC)
public class MQSeckillResultListener implements RocketMQListener<OrderMQResult> {

    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("现在进入通知队列");
        //睡一会防止token还没过来就返回消息了
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        String token = orderMQResult.getToken();
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        try {
            webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
